package com.bk.bookviews.exception;

import com.bk.bookviews.domain.ResultMsg;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
/**
 * @description 系统异常统一处理
 */
public class SystemExceptionHandler {

    //成功码
    private static final String SUCCESS_CODE = "000000";
    //失败码
    private static final String FAILED_CODE = "999999";

    //符号
    private static final String SYMBOL = "\\{\\}";

    private Logger logger = LoggerFactory.getLogger(SystemExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    /**
     * @author baojunjun
     * @date 2018-8-22
     * @description 转换异常信息为实体类对象
     * @param e  异常对象
     * @return  ResultMsg
     */
    public ResultMsg handler(Exception e){
    	
        ResultMsg resultMsg = new ResultMsg();
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String lang = request.getHeader("lang");
        if(e instanceof BusinessException){
            BusinessException businessException = (BusinessException) e;
            
            BusinessExceptionEnum businessExceptionEnum = businessException.getBusinessExceptionEnum();
            String code = "";
            String errMsg = "";
            if(businessExceptionEnum == null){
            	code = businessException.getCode();
            	errMsg = businessException.getErrMsg();
            }else{
            	code = String.valueOf(businessExceptionEnum.getCode());
            	if("en_us".equals(lang)){
                	errMsg = replaceArgs(businessException.getBusinessExceptionEnum().getEnUsErrMsg(),businessException.getArr());
                } else {
                	errMsg = replaceArgs(businessException.getBusinessExceptionEnum().getErrMsg(),businessException.getArr());
                }
            }
//            String code = String.valueOf(businessExceptionEnum.getCode());
//            String errMsg = "";
//            if("zh_cn".equals(lang)){
//            	errMsg = replaceArgs(businessException.getBusinessExceptionEnum().getErrMsg(),businessException.getArr());
//            } else {
//            	errMsg = replaceArgs(businessException.getBusinessExceptionEnum().getEnUsErrMsg(),businessException.getArr());
//            }
            resultMsg.setCode(code);
            resultMsg.setErrMsg(errMsg);
            logger.error("业务异常,错误码为:{},错误信息为:{}",code,errMsg);
            logger.error(ExceptionUtils.getStackTrace(e));
        } else {
        	logger.error(ExceptionUtils.getStackTrace(e));
            //其它异常给一个默认的失败码
            resultMsg.setCode(FAILED_CODE);
            if("en_us".equals(lang)){
                resultMsg.setErrMsg("System anomaly, please contact administrator！");
            } else {
                resultMsg.setErrMsg("系统异常，请联系管理员！");
            }
        }
        return resultMsg;
    }

    /**
     * @author baojunjun
     * @date 2018-8-22
     * @description 替换参数
     * @param sourceString  源字符串
     * @param arr   可变参数数组
     * @return  String
     */
    private String replaceArgs(String sourceString,Object arr[]){
        if(arr == null || arr.length == 0){
            return sourceString;
        }

        for(Object obj:arr){
            sourceString = sourceString.replaceFirst(SYMBOL,obj.toString());
        }
        return sourceString;
    }
}
